package com.nulldev.util.JVM.reflections.cache;

import java.util.Map;

import com.nulldev.util.data.Arrays.maps.trie.TrieMap;

final class ClassElementFactory {
	protected final Map<String, ClassElement> cacheClass = new TrieMap<String, ClassElement>();

	public final ClassElement getClass(final String name) {
		if (name == null || name.length() <= 0) {
			throw new CachedReflectException("Class name not specified.");
		}
		ClassElement ret = cacheClass.get(name);
		if (ret == null) {
			try {
				Class<?> c;
				if ((c = Class.forName(name)) != null) {
					ret = new ClassElement(c);
					cacheClass.put(name, ret);
				}
			} catch (Exception e) {
				throw new CachedReflectException(e);
			}
		}
		return ret;
	}

	public final ClassElement getClass(ClassLoader cl, String name) {
		if (name == null || name.length() <= 0) {
			throw new CachedReflectException("Class name not specified.");
		}
		ClassElement ret = cacheClass.get(name);
		if (ret == null) {
			try {
				Class<?> c;
				if (cl == null) {
					c = Class.forName(name);
				} else {
					c = cl.loadClass(name);
				}
				if (c != null) {
					ret = new ClassElement(c);
					cacheClass.put(name, ret);
				}
			} catch (Exception e) {
				throw new CachedReflectException(e);
			}
		}
		return ret;
	}
}
